#!/usr/bin/env python3
"""
检查是否有展开Key Features的按钮或机制
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
import time
import json

def find_expand_mechanism():
    """查找展开Key Features的机制"""
    
    chrome_options = Options()
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--window-size=1920,1080')
    # chrome_options.add_argument('--headless')
    
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=chrome_options)
    
    try:
        print("🔍 查找展开Key Features的机制...")
        
        # 访问页面并点击Titanium的View Specifications
        url = "https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-DH&planId=c"
        driver.get(url)
        
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, 'div[data-cy][class*="ProductTile"]'))
        )
        
        # 处理Cookie
        try:
            cookie_buttons = driver.find_elements(By.CSS_SELECTOR, 'button[id*="cookie"], button[class*="cookie"]')
            for btn in cookie_buttons:
                if btn.is_displayed():
                    btn.click()
                    time.sleep(1)
        except:
            pass
        
        # 找到Titanium并点击View Specifications
        titanium_element = driver.find_element(By.CSS_SELECTOR, 'div[data-cy="Titanium"]')
        spec_button = titanium_element.find_element(By.CSS_SELECTOR, 'button[data-cy="product-tile-overlay"]')
        ActionChains(driver).move_to_element(titanium_element).perform()
        time.sleep(1)
        driver.execute_script("arguments[0].click();", spec_button)
        time.sleep(3)
        
        print("✅ 已打开Titanium的规格页面")
        
        # 查找第一个Key Features部分
        key_feature_headers = driver.find_elements(By.XPATH, "//*[contains(text(), 'Key Features')]")
        if not key_feature_headers:
            print("❌ 未找到Key Features标题")
            return
        
        first_header = key_feature_headers[0]
        print(f"✅ 找到第一个Key Features部分")
        
        # 查找该部分的父容器
        try:
            parent_container = first_header.find_element(By.XPATH, "../..")
            print(f"✅ 找到父容器: {parent_container.tag_name}, class: {parent_container.get_attribute('class')}")
        except:
            parent_container = first_header.find_element(By.XPATH, "./..")
            print(f"✅ 找到父容器: {parent_container.tag_name}, class: {parent_container.get_attribute('class')}")
        
        # 查找初始的li元素数量
        initial_lis = parent_container.find_elements(By.CSS_SELECTOR, "li")
        print(f"初始li元素数量: {len(initial_lis)}")
        for i, li in enumerate(initial_lis[:5]):
            print(f"  {i+1}. {li.text}")
        
        # 查找可能的展开按钮
        expand_button_selectors = [
            'button[class*="expand"]',
            'button[class*="more"]',
            'button[class*="show"]',
            'button[aria-expanded="false"]',
            'button[class*="toggle"]',
            'a[class*="expand"]',
            'a[class*="more"]',
            'span[class*="expand"]',
            '*[class*="show-more"]',
            '*[class*="view-all"]',
            '*[class*="see-more"]'
        ]
        
        expand_buttons = []
        for selector in expand_button_selectors:
            try:
                buttons = parent_container.find_elements(By.CSS_SELECTOR, selector)
                for btn in buttons:
                    if btn.is_displayed():
                        expand_buttons.append({
                            'element': btn,
                            'selector': selector,
                            'text': btn.text,
                            'aria_expanded': btn.get_attribute('aria-expanded'),
                            'class': btn.get_attribute('class')
                        })
            except:
                continue
        
        print(f"\n🔍 找到 {len(expand_buttons)} 个可能的展开按钮:")
        for i, btn_info in enumerate(expand_buttons):
            print(f"  {i+1}. 选择器: {btn_info['selector']}")
            print(f"     文本: '{btn_info['text']}'")
            print(f"     aria-expanded: {btn_info['aria_expanded']}")
            print(f"     class: {btn_info['class']}")
        
        # 尝试点击每个可能的展开按钮
        for i, btn_info in enumerate(expand_buttons):
            print(f"\n🖱️  尝试点击第 {i+1} 个按钮...")
            
            try:
                # 记录点击前的状态
                before_lis = len(parent_container.find_elements(By.CSS_SELECTOR, "li"))
                
                # 点击按钮
                btn = btn_info['element']
                driver.execute_script("arguments[0].click();", btn)
                time.sleep(2)
                
                # 检查点击后的状态
                after_lis = len(parent_container.find_elements(By.CSS_SELECTOR, "li"))
                
                print(f"     点击前li数量: {before_lis}")
                print(f"     点击后li数量: {after_lis}")
                
                if after_lis > before_lis:
                    print(f"     ✅ 成功！增加了 {after_lis - before_lis} 个li元素")
                    
                    # 显示新增的元素
                    current_lis = parent_container.find_elements(By.CSS_SELECTOR, "li")
                    print("     新的完整列表:")
                    for j, li in enumerate(current_lis):
                        text = li.text.strip()
                        if text:
                            print(f"       {j+1}. {text}")
                    
                    # 保存成功的方法
                    success_result = {
                        'success': True,
                        'button_selector': btn_info['selector'],
                        'button_text': btn_info['text'],
                        'initial_count': before_lis,
                        'final_count': after_lis,
                        'all_features': [li.text.strip() for li in current_lis if li.text.strip()]
                    }
                    
                    with open('./release/expand_success_result.json', 'w', encoding='utf-8') as f:
                        json.dump(success_result, f, ensure_ascii=False, indent=2)
                    
                    print("💾 成功结果已保存到 ./release/expand_success_result.json")
                    return success_result
                else:
                    print(f"     ❌ 无效果")
                    
            except Exception as e:
                print(f"     ❌ 点击失败: {e}")
        
        # 如果没有找到展开按钮，尝试其他交互方式
        print(f"\n🔍 尝试其他交互方式...")
        
        # 尝试双击Key Features标题
        try:
            print("尝试双击Key Features标题...")
            ActionChains(driver).double_click(first_header).perform()
            time.sleep(2)
            
            after_lis = len(parent_container.find_elements(By.CSS_SELECTOR, "li"))
            if after_lis > len(initial_lis):
                print(f"✅ 双击标题成功！新增了 {after_lis - len(initial_lis)} 个li元素")
        except Exception as e:
            print(f"双击失败: {e}")
        
        # 尝试右键点击
        try:
            print("尝试右键点击Key Features区域...")
            ActionChains(driver).context_click(parent_container).perform()
            time.sleep(2)
        except Exception as e:
            print(f"右键点击失败: {e}")
        
        # 检查是否有隐藏的内容可以通过CSS显示
        try:
            print("检查隐藏的CSS内容...")
            driver.execute_script("""
                var elements = document.querySelectorAll('*[style*="display: none"], *[style*="visibility: hidden"], *[class*="hidden"]');
                for (var i = 0; i < elements.length; i++) {
                    if (elements[i].textContent.includes('Electrically Operated') || 
                        elements[i].textContent.includes('Lane-Keeping') ||
                        elements[i].textContent.includes('Pre-Collision')) {
                        elements[i].style.display = 'block';
                        elements[i].style.visibility = 'visible';
                        console.log('Found hidden Key Features element:', elements[i]);
                    }
                }
            """)
            time.sleep(1)
            
            final_lis = parent_container.find_elements(By.CSS_SELECTOR, "li")
            if len(final_lis) > len(initial_lis):
                print(f"✅ 显示隐藏内容成功！")
        except Exception as e:
            print(f"显示隐藏内容失败: {e}")
        
        # 最终统计
        final_lis = parent_container.find_elements(By.CSS_SELECTOR, "li")
        print(f"\n📊 最终统计:")
        print(f"  初始li数量: {len(initial_lis)}")
        print(f"  最终li数量: {len(final_lis)}")
        print(f"  期望li数量: 17 (根据用户提供的数据)")
        
        if len(final_lis) < 17:
            print("❌ 仍然无法获取完整的Key Features列表")
            print("可能需要进入单独的详情页面才能看到完整列表")
        
    except Exception as e:
        print(f"❌ 查找过程中出现异常: {e}")
        import traceback
        traceback.print_exc()
        
    finally:
        print("🧹 清理资源...")
        driver.quit()

if __name__ == "__main__":
    find_expand_mechanism()
